package com.authority.service.impl;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.authority.dao.AuthActionDAO;
import com.authority.dao.AuthUserDAO;
import com.authority.entry.AuthActionDO;
import com.authority.query.AuthActionQuery;
import com.authority.result.PageResult;
import com.authority.service.AuthActionService;
import com.authority.utils.CommonUtils;
import com.authority.utils.CommonUtils.CallBack;
import com.authority.vo.AuthActionVO;
import com.authority.vo.IdNameVO;
import com.google.common.collect.Lists;

/**
 * 
 * @author limeng.g
 *
 */
@Service("authActionService")
@Transactional(rollbackFor = Exception.class)
public class AuthActionServiceImpl implements AuthActionService {

	@Resource
	private AuthActionDAO authActionDAO;

	@Resource
	private AuthUserDAO userDAO;

	@Override
	public PageResult<AuthActionVO> listAuthAction(AuthActionQuery query) throws Exception {

		List<AuthActionVO> list = CommonUtils.dbToVo(authActionDAO.queryAuthAction(query), AuthActionVO.class, new CallBack<AuthActionDO, AuthActionVO>() {
			@Override
			public void execute(AuthActionDO db, AuthActionVO vo) {
				vo.setOperator(userDAO.queryUserNameById(db.getOperatorId())); // 操作人
			}
		});

		return PageResult.create(list, authActionDAO.queryAuthActionCount(query), query.getIndex(), query.getNum());
	}

	@Override
	public AuthActionDO getAuthActionById(Long id) {

		return authActionDAO.queryAuthActionById(id);
	}

	@Override
	public Long saveAuthAction(AuthActionDO authActionDO) throws Exception {

		AuthActionDO db = authActionDAO.queryAuthActionBySysIdAndCode(authActionDO.getCode(), authActionDO.getSysId());
		if (db != null) {
			throw new Exception("功能编码不能重复");
		}

		return authActionDAO.insertAuthAction(authActionDO);
	}

	@Override
	public int updateAuthAction(AuthActionDO authActionDO) {

		return authActionDAO.updateAuthAction(authActionDO);
	}

	@Override
	public List<IdNameVO> listAuthActionIdName(Long sysId) {

		List<AuthActionDO> list = authActionDAO.queryAuthActionBySysId(sysId);
		List<IdNameVO> vos = Lists.newArrayList();

		if (!CollectionUtils.isEmpty(list)) {
			for (AuthActionDO db : list) {
				vos.add(new IdNameVO(db.getId(), db.getName()));
			}
		}
		return vos;
	}

}
